<?php

include 'includes/general.init.php';

$tpl->page = 'register';

if ($user->is_logged_in)
{
	redirect('index.php');
}

if (set::get('allow_registration') == true)
{
	
	if(!empty($_POST))
	{
		$recaptcha_resp = null;
		$recaptcha_error = null;
		$recaptcha_resp = recaptcha_check_answer (set::get('recaptcha_private_key'),
                                $_SERVER['REMOTE_ADDR'],
                                $_POST['recaptcha_challenge_field'],
                                $_POST['recaptcha_response_field']);

		if ($recaptcha_resp->is_valid)
		{
			if ($_POST['user'] == sanitize_user($_POST['user']))
			{
				$exist = $user->get_info('user', $_POST['user'], array('id'));
				if ($exist == false)
				{
					if ($_POST['pass'] == $_POST['conf_pass'])
					{
						// Three "=" 's here. It all returns true. So we want
						// to make sure that the true it returns, is actually
						// true.
						if (is_email($_POST['email']) === true)
						{
							$salt = $user->gen_salt();
							$pass = $user->gen_pass($_POST['pass'], $salt);
							$query = 'INSERT INTO users (`user`, `pass`, `salt`, `email`, `rank`) VALUES (
									"'.$db->escape($_POST['user']).'", "'.$db->escape($pass).'",
									"'.$db->escape($salt).'", "'.$db->escape($_POST['email']).'",
									"user");';
							$result = $db->query($query);
							if ($result)
							{
								$tpl->message = 'You have been successfully registered. You can log in now.';
							}
							else
							{
								$tpl->message = 'There was an error trying to enter your information into the database.';
							}
						}
						else
						{
							$tpl->message = 'You have entered an invalid email address.';
						}
					}
					else
					{
						$tpl->message = 'The two passwords you have entered do not match.';
					}
				}
				else
				{
					$tpl->message = 'A user with that username already exists.';
				}
			}
			else
			{
				$tpl->message = 'There are invalid characters in the username you have chose.';
			}
		}
		else
		{
			$tpl->message = 'The reCaptcha you have entered was entered incorrectly. ' . br;
			$tpl->message .= 'reCaptcha said: ' . $recaptcha_resp->error . br . br;
		}
	}
}
else
{
	$tpl->message = 'Registration is disabled.';
}

$tpl->display('header.php');
$tpl->display('sidebar.php');
$tpl->display('page_register.php');
$tpl->display('footer.php');

session::clear_old();